# _*_ coding:utf-8 _*_
import json
from django.shortcuts import render
from django.views.generic.base import View
from .models import Blog, Comment, BlogFavorite, MessageBoard
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from django.db.models import Q
from .forms import CommentForm, MessageBoardForm
from datetime import datetime

# Create your views here.


class Index(View):

    def get(self, request):
        articles = Blog.objects.all()
        # 分页
        keywords = request.GET.get('keywords', '')
        if keywords:
            articles = Blog.objects.filter(Q(title__contains=keywords) | Q(desc__contains=keywords))
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        print page
        p = Paginator(articles, 20, request=request)
        arts = p.page(page)
        return render(request, 'article_list.html', {'articles': arts})


class Content(View):
    def get(self, request, page_num):
        article = Blog.objects.get(id=page_num)
        comments = Comment.objects.filter(article_id=article.id)
        fav_nums = BlogFavorite.objects.filter(article_id=article.id).count()
        count = comments.count()
        return render(request, 'article_content.html', {'article': article, 'comments': comments,
                                                        'count': count, 'fav_nums': fav_nums})


class AddComment(View):

    def post(self, request):
        article_id = request.POST.get('arcticle_id', 0)
        comment = request.POST.get('comment', '')
        author = request.POST.get('author', '')
        email = request.POST.get('email', '')
        is_exist_blog = Blog.objects.filter(id=int(article_id))
        if is_exist_blog:
            if article_id and comment and author and email:
                blog_comment = Comment()
                blog_comment.article = Blog.objects.get(id=article_id)
                blog_comment.content = comment
                blog_comment.email = email
                blog_comment.nick_name = author
                blog_comment.save()
                return HttpResponse(
                    json.dumps({
                        'status': 'success',
                        'msg': '评论成功',
                    }), content_type='application/json')

        return HttpResponse(
            json.dumps({
                'status': 'fail',
                'msg': '邮箱格式不对哦，请仔细核对！',
            }), content_type='application/json')


class AddFavorite(View):

    def post(self, request):
        article_id = request.POST.get('article_id', 0)
        is_exists = Blog.objects.filter(id=article_id)
        if is_exists:
            blog_fav = BlogFavorite()
            blog_fav.article = Blog.objects.get(id=article_id)
            blog_fav.fav_nums += 1
            blog_fav.save()
            return HttpResponse(
                json.dumps({
                    'status': 'success',
                    'msg': '评论成功',
                })
            )
        return HttpResponse(
            json.dumps({
                'status': 'fail',
                'msg': '点赞失败'
            })
        )


class MessageBoards(View):
    def get(self, request):
        return render(request, 'mboard.html', {})

    def post(self, request):
        board_form = MessageBoardForm(request.POST)
        if board_form.is_valid():
            board_form.save()
            # name = request.POST.get('name', '')
            # email = request.POST.get('email', '')
            # address = request.POST.get('address', '')
            # message = request.POST.get('message', '')
            # if name and email and address and message:
            #     mBoard = MessageBoard()
            #     mBoard.name = name
            #     mBoard.email = email
            #     mBoard.address = address
            #     mBoard.message = message
            return HttpResponse(
                json.dumps({
                    'status': 'success',
                    'msg': '留言成功,谢谢您的反馈，祝生活愉快！',
                })
            )
        return HttpResponse(
            json.dumps({
                'status': 'fail',
                'msg': '请检查邮箱填写是否正确，若正确请与管理员联系。',
            })
        )


def page_not_found(request):
    """全局404"""
    from django.shortcuts import render_to_response
    response = render_to_response('404.html', {})
    response.status_code = 404
    return response


def page_error(request):
    """全局500"""
    from django.shortcuts import render_to_response
    response = render_to_response('500.html', {})
    response.status_code = 500
    return response
